<?php 
namespace app\api\controller;

use app\api\ApiController;
use common\service\AuthService;
use common\service\SteamUtilService;
use common\service\UserService;
use common\service\CaptchaService;
use common\service\VerifyService;
use common\service\InviteLogService;
use think\Request;

/**
 * 
 * @author Administrator
 *
 */
class User extends ApiController
{

    public function checkWalletAddress(){
        $steamInfo = AuthService::getInstance()->verifyToken();
        if(empty($steamInfo)){
            return $this->errorMessage(BAD_ACCESS_TOKEN_NO, BAD_ACCESS_TOKEN_ERROR);
        }
        $userId = $steamInfo['user_id'];
        $result = UserService::getInstance()->checkWalletAddress($userId);
        if($result == true){
            return $this->successJson($result);
        }
        return $this->errorMessage(NOTEXIST_WALLETADDRESS_NO, NOTEXIST_WALLETADDRESS_ERROR);
    }

	public function verifyTradePwd($traderPwd){
		$steamInfo = AuthService::getInstance()->verifyToken();
		if(empty($steamInfo)){
			return $this->errorMessage(BAD_ACCESS_TOKEN_NO, BAD_ACCESS_TOKEN_ERROR);
		}
		$userId = $steamInfo['user_id'];
		if(!UserService::getInstance()->checkTradePwd($userId, $traderPwd)){
			return $this->errorMessage(USER_TRANS_PWD_ERR,USER_TRANS_PWD_ERR_ERROR);
		}
		return $this->successJson();
	}
	public function checkTradePwd(){
		$steamInfo = AuthService::getInstance()->verifyToken();
		if(empty($steamInfo)){
			return $this->errorMessage(BAD_ACCESS_TOKEN_NO, BAD_ACCESS_TOKEN_ERROR);
		}
		$userId = $steamInfo['user_id'];
		$result = UserService::getInstance()->checkSetTradePwd($userId);
		if($result == true){
			return $this->successJson();
		}
		return $this->errorMessage(USER_TRANS_PWD_NO_SET,USER_TRANS_PWD_NO_SET_ERROR);
	}
	public function checktradeurl(){
		$steamInfo = AuthService::getInstance()->verifyToken();
		if(empty($steamInfo)){
			return $this->errorMessage(BAD_ACCESS_TOKEN_NO, BAD_ACCESS_TOKEN_ERROR);
		}
        $steamId = $steamInfo['steam_id'];
        $steamUser = UserService::getInstance()->getUserInfoBySteamId($steamId);
        $tradeUrl = $steamUser['trade_off_url'];
		if(empty($tradeUrl)){
			return $this->errorMessage(TRADEURL_NOTEXIST_NO, TRADEURL_NOTEXIST_ERROR);
		}else{
            return $this->successJson(['tradeUrl'=>$tradeUrl]);
        }
//		$result = SteamBotService::getInstance()->getPartnerTradeEscrow($tradeUrl);
//		if($result){
//			return $this->successJson(['tradeUrl'=>$tradeUrl]);
//		}
		return $this->errorMessage(TRADEURL_CHECK_NO);
	}
	
    /**
     * @api {post} /user/setTradeUrl 设置用户steam交易链接
     * @apiVersion 1.0.0
     * @apiName setTradeUrl
     * @apiGroup user
     *
     * @apiDescription   设置用户steam交易链接
     *
     **@apiParam {String} tradeUrl steam steam交易链接
     *
     * @apiError 20000 请求参数错误
     *
     * @apiErrorExample Response (errorExample)
     * {
     *	code: 30005,
     *	msg: "交易链接格式错误"
     * }
     * @apiSuccessExample Response (example):
     *  {
     *		code: 99999,
     *		msg: "设置成功"
     *	}
     */
	public function setTradeUrl($tradeUrl = null)
    {
        $result = $this->validate(
            [
                'tradeUrl'  => $tradeUrl,
            ],
            [
                'tradeUrl'  => 'require|url',
            ],
            [
                'tradeUrl.require' => '交易链接不能为空',
                'tradeUrl.url' => '交易链接格式错误'
            ]
        );
        if(true !== $result){
            // 验证失败 输出错误信息
            return $this->errorParams($result);
        }
        $steamInfo = AuthService::getInstance()->verifyToken();
        if (!preg_match('/^https:\/\/steamcommunity.com\/tradeoffer\/new\/\?partner=(\d+)&token=([a-z0-9_\-]{1,20})$/i', $tradeUrl, $matches)){
            return $this->errorMessage(TRADEURL_FORMAT_NO, TRADEURL_FORMAT_ERROR);
        }
        if (SteamUtilService::getInstance()->toCommunityID($matches[1]) != $steamInfo['steam_id']) {
            return $this->errorMessage(TRADEURL_MATCH_NO, TRADEURL_MATCH_ERROR);
        }
//        try {
//            SteamBotService::getInstance()->getPartnerTradeEscrow($tradeUrl);
//        }catch(\Exception $e) {
//            $code = $e->getCode();
//            $msg = $e->getMessage();
//            if($code != 1) {
//                $msg = '交易链接检查失败';
//            }
//            return $this->errorMessage(TRADEURL_CHECK_NO, TRADEURL_CHECK_ERROR);
//        }
        $trade_token = $matches[2];
        
        $result = UserService::getInstance()->setTradeUrl($steamInfo['user_id'], $steamInfo['steam_id'], $tradeUrl,$trade_token);
           
        if($result){
            return $this->successJson(['tradeUrl'=>$tradeUrl]);
        }else{
            return $this->errorMessage(TRADEURL_SET_NO, TRADEURL_SET_ERROR);
        }

    }
	
    /**
     * @api {post} /user/feedback  用户反馈
     * @apiVersion 1.0.0
     * @apiName feedback
     * @apiGroup user
     *
     * @apiDescription   用户反馈
     *
     * @apiParam {String} access_token token 
     * @apiParam {String} message 反馈
     * @apiParam {String} captcha 验证码
     * @apiError 20000 请求参数错误
     *
     * @apiErrorExample Response (errorExample)
     * {
     *	code: 2000,
     *	msg: "参数错误"
     * }
     * @apiSuccessExample Response (example):
     *  {
     *		code: 99999,
     *		msg: "设置成功"
     *	}
     */
    public function feedback($email = null,$qq = '',$mobile = '',$message = null,$code = null){
   	 	$result = $this->validate(
 				[
 				    'email' => $email,
                    'qq' => $qq,
                    'mobile' => $mobile,
 				    'message'  => $message,
   	 			    'code'=> $code
                ],
 				[
                    'email' => 'require|email',
                    'qq' => 'number|length:5,12',
                    'mobile' => 'number|length:11',
 				    'message'  => 'require|max:500',
   	 			    'code'  => 'require|length:4'
   	 			],
                [
                    'email.require' => '邮箱不能为空',
                    'email.email' => '邮箱格式不正确',
                    'mobile.number' => '手机号码格式不正确',
                    'mobile.length' => '手机号码格式不正确',
                    'message.require' => '问题描述不能为空',
                    'message.max' => '问题描述超出长度限制',
                    'code.require' => '验证码不能为空',
                    'code.length' => '验证码格式错误',
                ]
 				);
        $user = AuthService::getInstance()->verifyToken();
        if(empty($user)){
            return $this->errorMessage(BAD_ACCESS_TOKEN_NO,BAD_ACCESS_TOKEN_ERROR);
        }
        $userId = $user['user_id'];
 		if(true !== $result){
 			// 验证失败 输出错误信息
 			return $this->errorParams($result);
 		}
 		if(!CaptchaService::getInstance()->checkVerify($userId, $code, 'feedback')){
 			return $this->errorMessage(BAD_CAPTCHA_NO,BAD_CAPTCHA_ERROR);
        }
 		$result = UserService::getInstance()->addFeedback($userId,$message,$email,$qq,$mobile);

        if($result){
            return $this->successJson($result);
        }else{
            return $this->errorMessage(SUBMIT_FAIL_NO, SUBMIT_FAIL_ERROR);
        }
    }

    //验证是否有邮箱
    public function checkEmail()
    {
        $user = AuthService::getInstance()->verifyToken();
        if(empty($user)){
            return $this->errorMessage(BAD_ACCESS_TOKEN_NO,BAD_ACCESS_TOKEN_ERROR);
        }
        $email = UserService::getInstance()->hasEmail($user['user_id']);
        if($email){
            return $this->successJson($email);
        }else{
            return $this->errorMessage(NOT_EMAIL_NO, NOT_EMAIL_ERROR);
        }
    }

    /**
     * @api {post} /user/userSetTradePwd 设置用户交易密码
     * @apiVersion 1.0.0
     * @apiName userSetTradePwd
     * @apiGroup user
     *
     * @apiDescription   设置用户交易密码
     *
     * @apiParam {String} access_token token
     * @apiParam {String} transPwd  交易密码
     * @apiParam {String} reptradePwd 重复交易密码
     * @apiParam {String} verify 验证码 验证码
     * 
     * @apiError 20000 请求参数错误
     *
     * @apiErrorExample Response (errorExample)
     * {
     *	code: 2000,
     *	msg: "参数错误"
     * }
     * @apiSuccessExample Response (example):
     *  {
     *		code: 99999,
     *		msg: "设置成功"
     *	}
     */
    public function userSetTradePwd($transPwd = null, $reptransPwd = null, $email = null, $verify = null, $inviteCode = null)
    {
        if(!Request::instance()->isPost()){
            return $this->errorMessage(REQUEST_NO,REQUEST_ERROR);
        }
        $result = $this->validate([
            'transPwd' => $transPwd,
            'reptransPwd' => $reptransPwd,
            'email' => $email,
            'verify' => $verify
        ],[
            'transPwd' => 'require|number|length:6',
            'reptransPwd' => 'require|number|length:6|confirm:transPwd',
            'email' => 'require|email',
            'verify' => 'require|alphaNum|length:6'
        ],[
            'transPwd.require' => '交易密码不能为空',
            'transPwd.number' => '交易密码格式错误',
            'transPwd.length' => '交易密码格式错误',
            'reptransPwd.require' => '确认交易密码不能为空',
            'reptransPwd.number' => '确认交易密码格式错误',
            'reptransPwd.length' => '确认交易密码格式错误',
            'reptransPwd.confirm' => '确认交易密码与交易密码不相同',
            'email.require' => '邮箱不能为空',
            'email.email' => '邮箱格式不正确',
            'verify.require' => '验证码不能为空',
            'verify.alphaNum' => '验证码格式错误',
            'verify.length' => '验证码格式错误'
        ]);
        if(true !== $result){
            // 验证失败 输出错误信息
            return $this->errorParams($result);
        }
        
        $user = AuthService::getInstance()->verifyToken();
        if(empty($user)){
        	return $this->errorMessage(BAD_ACCESS_TOKEN_NO,BAD_ACCESS_TOKEN_ERROR);
        }
		$userId = $user['user_id'];
        $res = VerifyService::getInstance()->checkVerify($email, $verify, 'stp');
        if($res!==true){
            return $this->errorMessage(BAD_CAPTCHA_NO, $res);
        }
        // cheack email
        $emailError = UserService::getInstance()->checkEmail($userId, $email);
        if($emailError !== true){
            if($emailError == -1){
                return $this->errorMessage(EMAIL_NOTMATCH_NO, EMAIL_NOTMATCH_ERROR);
            }elseif($emailError == -2){
                return $this->errorMessage(EMAIL_EXIST_NO, EMAIL_EXIST_ERROR);
            }
        }

        if ($inviteCode) {
            $res = InviteLogService::getInstance()->setInviteCode($userId, $inviteCode);
            if ($res == -1) {
                return $this->errorMessage(INVITE_CODE_USER_NO, INVITE_CODE_USER_ERROR);
            } elseif ($res == -2) {
                return $this->errorMessage(INVITE_CODE_CHECK_USER_NO, INVITE_CODE_CHECK_USER_ERROR);
            } elseif ($res == -3) {
                return $this->errorMessage(INVITE_CODE_CHECK_USER2_NO, INVITE_CODE_CHECK_USER2_ERROR);
            } elseif ($res == -4) {
                return $this->errorMessage(INVITE_CODE_SET_NO, INVITE_CODE_SET_ERROR);
            }
        }

        $result = UserService::getInstance()->saveUserTransactionPwd($userId, $transPwd, $email);

        if($result){
            return $this->successJson();
        }else{
            return $this->errorMessage(SETTING_NO, SETTING_ERROR);
        }
    }

}

?>